package com.thd.kc.controller;


import com.thd.kc.constants.CommonConstants;
import com.thd.kc.constants.DictClassifyEnum;
import com.thd.kc.dto.ArticleDto;
import com.thd.kc.dto.AttachDto;
import com.thd.kc.dto.DictDto;
import com.thd.kc.dto.Message;
import com.thd.kc.service.KcService;
import com.thd.kc.utils.AssertUtils;
import com.thd.kc.utils.FileUtils;
import com.thd.kc.utils.UuidUtils;
import com.thd.kc.vuedto.VueSelectDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/kc")
public class KcController {

    @Autowired
    private KcService kcService;

    @Autowired
    private WebApplicationContext webApplicationContext;

    Logger logger = LoggerFactory.getLogger(KcController.class);
    @RequestMapping("/test")
    @ResponseBody
    // url : http://127.0.0.1:8899/kc/test
    public Message test(){
        System.out.println("test5");
        logger.info("test");

        return Message.success();
    }


    @PostMapping("/saveOrUpdateArticle")
    @ResponseBody
    // url : http://127.0.0.1:8899/kc/saveOrUpdateArticle
    public Message<ArticleDto>  saveOrUpdateArticle(@RequestBody ArticleDto articleDto){
        System.out.println("saveOrUpdateArticle");
        logger.info("saveOrUpdateArticle");
        ArticleDto r = this.kcService.saveOrUpdateArticle(articleDto);

        try{
            this.kcService.createWordCloud(r);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
        return Message.success(r);
    }

    @PostMapping("/queryArticleList")
    @ResponseBody
    // url : http://127.0.0.1:8899/kc/queryArticleList
    public Message<List<ArticleDto>>  queryArticleList(@RequestBody ArticleDto articleDto){
//        System.out.println("queryArticleList");
        logger.info("queryArticleList");
        List<ArticleDto> r = new ArrayList<ArticleDto>();
        if(CommonConstants.QUERY_TYPE__DB.equals(articleDto.getQueryType())){
            r = this.kcService.queryArticleListByDb(articleDto);
        }else{
            r = this.kcService.queryArticleListByLucene(articleDto);
        }
        return Message.success(r);
    }

    @PostMapping("/queryArticleListTotal")
    @ResponseBody
    // url : http://127.0.0.1:8899/kc/queryArticleListTotal
    public Message<List<ArticleDto>>  queryArticleListTotal(@RequestBody ArticleDto articleDto){
//        System.out.println("queryArticleListTotal");
        logger.info("queryArticleListTotal");
        Integer ct = 0;
        if(CommonConstants.QUERY_TYPE__DB.equals(articleDto.getQueryType())){
            ct = this.kcService.queryArticleListTotalByDb(articleDto);
        }else{
            ct = this.kcService.queryArticleListTotalByLucene(articleDto);
        }



        return Message.success(ct);
    }






    @GetMapping("/queryArticleById/{id}")
    @ResponseBody
    // url : http://127.0.0.1:8899/kc/queryArticleById/1
    public Message<ArticleDto>  queryArticleById(@PathVariable String id){
//        System.out.println("queryArticleById");
        logger.info("queryArticleById");
        ArticleDto r = this.kcService.queryArticleById(id);
        return Message.success(r);
    }

    @GetMapping("/deleteArticle/{id}")
    @ResponseBody
    // url : http://127.0.0.1:8899/kc/deleteArticle/1
    public Message  deleteArticle(@PathVariable String id){
//        System.out.println("deleteArticle");
        logger.info("deleteArticle");
        this.kcService.deleteArticle(id);
        return Message.success();
    }




    @PostMapping("/upload")
    @ResponseBody
    public Message<String> uploadFile(MultipartFile file, @RequestParam String folderName) throws Exception {
        AssertUtils.stringIsNotEmpty(folderName,"FolderName can not be empty");
        logger.info("folder:" + folderName);
        String jarPathStr = System.getProperty("user.dir");
        logger.info("jar file path : " + jarPathStr);

        Path jarPath = new File(jarPathStr).toPath();
        String folderFullPath = jarPathStr + File.separator + "localfile"+ File.separator + "mdimgs" + File.separator + folderName;
        File f = new File(folderFullPath);

        int fileCount = 1;
        if(!f.exists()){
            f.mkdirs();
        }else{
            fileCount = f.listFiles().length+1;
        }
        String baseCode = "000";

        String fileName = baseCode.substring(0,baseCode.length() - String.valueOf(fileCount).length()) + fileCount + "." + FileUtils.getFileSufix(file.getOriginalFilename());

        String targetFilePath = folderFullPath + File.separator +  fileName;

        InputStream inputStream = file.getInputStream();
        FileUtils.writeFile(inputStream, targetFilePath);

        ServletWebServerApplicationContext context = (ServletWebServerApplicationContext) webApplicationContext;

        String downloadFilePath =  "http://127.0.0.1:"+ context.getWebServer().getPort()  +"/kc/downloadByPath?filePath=" + folderName + "/" +  fileName;
        logger.info(downloadFilePath);
        return Message.success(downloadFilePath);
    }

    @GetMapping("/downloadByPath")
    @ResponseBody
    public void downloadByPath(@RequestParam String filePath, HttpServletResponse response) throws Exception {
        String jarPathStr = System.getProperty("user.dir");
        logger.info("jar file path : " + jarPathStr);

        Path jarPath = new File(jarPathStr).toPath();

        String targetFilePath =  jarPathStr + File.separator + "localfile"+ File.separator + "mdimgs" + File.separator +  filePath;
        File f = new File(targetFilePath);

        response.setContentType("application/force-download");// 设置强制下载不打开
        response.addHeader("Content-Disposition", "attachment;fileName=" + FileUtils.getFileName(targetFilePath));
        logger.info(f.toURI().toString());
        Files.copy(Path.of(f.toURI()), response.getOutputStream());
        response.getOutputStream().close();
    }




    @PostMapping("/uploadAttach")
    @ResponseBody
    public Message<String> uploadAttach(MultipartFile file, @RequestParam String relaId,@RequestParam(required = false) String classify) throws Exception {
        AssertUtils.stringIsNotEmpty(relaId,"RelaId can not be empty");
        logger.info("relaId:" + relaId);
        String jarPathStr = System.getProperty("user.dir");
        logger.info("jar file path : " + jarPathStr);

        Path jarPath = new File(jarPathStr).toPath();
        String folderFullPath = jarPathStr + File.separator + "localfile"+ File.separator + "attach" + File.separator + relaId;
        File f = new File(folderFullPath);

        int fileCount = 1;
        if(!f.exists()){
            f.mkdirs();
        }else{
            fileCount = f.listFiles().length+1;
        }
        String baseCode = "000";

        String fileName = baseCode.substring(0,baseCode.length() - String.valueOf(fileCount).length()) + fileCount + "." + FileUtils.getFileSufix(file.getOriginalFilename());

        String targetFilePath = folderFullPath + File.separator +  fileName;

        InputStream inputStream = file.getInputStream();
        FileUtils.writeFile(inputStream, targetFilePath);

        AttachDto attach = new AttachDto();
        attach.setId(UuidUtils.uuid());
        attach.setClassify(classify);
        attach.setFileName(FileUtils.getFilePrefix(file.getOriginalFilename()));
        attach.setSuffix(FileUtils.getFix(fileName));
        attach.setFilePath("/"+ relaId + "/" + fileName );
        attach.setRelaId(relaId);
        this.kcService.saveAttach(attach);
        return Message.success("SUCCESS");
    }

    @GetMapping("/queryDict/{classify}")
    @ResponseBody
    // url : http://127.0.0.1:8899/kc/queryDict/ARTICLE_CLASSIFY
    public Message<List<VueSelectDto>>  queryDict(@PathVariable String classify){
//        System.out.println("queryDict");
        logger.info("queryDict");
        List<VueSelectDto> r = this.kcService.queryDict(classify);
        return Message.success(r);
    }

    @PostMapping("/queryArticleTags")
    @ResponseBody
    // url : http://127.0.0.1:8899/kc/queryArticleTags
    public Message<List<VueSelectDto>>  queryArticleTags(@RequestBody DictDto dictDto){
//        System.out.println("queryDict");
        logger.info("queryDict");
        List<VueSelectDto> r = this.kcService.queryArticleTags(DictClassifyEnum.TAG.name(), dictDto.getTitle());
        return Message.success(r);
    }

    @GetMapping("/indexAllArticle")
    @ResponseBody
    // url : http://127.0.0.1:8899/kc/indexAllArticle
    public Message<String>  indexAllArticle(){
//        System.out.println("indexAllArticle");
        logger.info("indexAllArticle");
        this.kcService.indexAllArticle();
        return Message.success();
    }

    @GetMapping("/indexArticleById/{articleId}")
    @ResponseBody
    // url : http://127.0.0.1:8899/kc/indexArticleById
    public Message<String>  indexArticleById(@PathVariable String articleId){
//        System.out.println("indexArticleById");
        logger.info("indexArticleById");
        this.kcService.indexArticleById(articleId);
        return Message.success();
    }

    @GetMapping("/deleteAttach/{attachId}")
    @ResponseBody
    // url : http://127.0.0.1:8899/kc/deleteAttach
    public Message<String>  deleteAttach(@PathVariable String attachId){
//        System.out.println("indexArticleById");
        logger.info("deleteAttach");
        this.kcService.deleteAttach(attachId);
        return Message.success();
    }


    @PostMapping("/queryAttachList")
    @ResponseBody
    // url : http://127.0.0.1:8899/kc/queryAttachList
    public Message<List<AttachDto>>  queryAttachList(@RequestBody AttachDto attachDto){
        logger.info("queryAttachList");
        List<AttachDto> r = this.kcService.queryAttachListByRelaIdAndClassify(attachDto.getRelaId(),attachDto.getClassify());
        return Message.success(r);
    }

    @GetMapping("/downloadAttach/{attachId}")
    @ResponseBody
    public void downloadAttach(@PathVariable String attachId, HttpServletResponse response) throws Exception {
        String jarPathStr = System.getProperty("user.dir");
        logger.info("jar file path : " + jarPathStr);

        AttachDto attach = kcService.queryAttachById(attachId);
        Path jarPath = new File(jarPathStr).toPath();

        String targetFilePath =  jarPathStr + File.separator + "localfile"+ File.separator + "attach" + attach.getFilePath() ;
        File f = new File(targetFilePath);

        response.setContentType("application/force-download");// 设置强制下载不打开
        response.addHeader("Content-Disposition", "attachment;fileName=" + FileUtils.getFileName(attach.getFileName()));
        logger.info(f.toURI().toString());
        Files.copy(Path.of(f.toURI()), response.getOutputStream());
        response.getOutputStream().close();
    }












}
